package com.ninong.ker.common.oss.config;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ListPartsRequest;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.PartListing;
import com.aliyun.oss.model.PartSummary;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 鸠摩智 Oss上传工具函数
 */
@Slf4j
public class OssTools {

	
	/**
	 * 获取新的上传id
	 * 
	 * @param bucketName bucketName
	 * @param key key
	 * @param client client
	 * @return  GenericResult
	 */
	public static String claimUploadId(String bucketName, String key, OSSClient client) {
		InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, key);
		InitiateMultipartUploadResult result = client.initiateMultipartUpload(request);
		return result.getUploadId();
	}

	public static File createSampleFile() throws IOException {
		File file = File.createTempFile("oss-java-sdk-", ".txt");
		file.deleteOnExit();

		Writer writer = new OutputStreamWriter(new FileOutputStream(file));
		int num =1000000;
		for (int i = 0; i < num ; i++) {
			writer.write("abcdefghijklmnopqrstuvwxyz\n");
			writer.write("0123456789011234567890\n");
		}
		writer.close();

		return file;
	}

	public static void listAllParts(String uploadId,String bucketName, String key, OSSClient client) {
		log.info("列出所有部分......");
		ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, key, uploadId);
		PartListing partListing = client.listParts(listPartsRequest);

		int partCount = partListing.getParts().size();
		for (int i = 0; i < partCount; i++) {
			PartSummary partSummary = partListing.getParts().get(i);
			log.info("\tPart#" + partSummary.getPartNumber() + ", ETag=" + partSummary.getETag());
		} 
	}
	
	public static void completeMultipartUpload(String uploadId,List<PartETag> partTags,String bucketName, String key, OSSClient client) {
	        // 按升序制作零件编号
	        Collections.sort(partTags, new Comparator<PartETag>() {

	            @Override
	            public int compare(PartETag p1, PartETag p2) {
	                return p1.getPartNumber() - p2.getPartNumber();
	            }
	        });
	        
	        log.info("完成上传多部分\n");
	        CompleteMultipartUploadRequest completeMultipartUploadRequest = 
	                new CompleteMultipartUploadRequest(bucketName, key, uploadId, partTags);
	        client.completeMultipartUpload(completeMultipartUploadRequest);
	    }
}
